package cn.itsource;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 自定义过滤器-做登录校验
 */
@Component
@Order(1)
public class LoginCheckFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);

    //过滤器类型，一般选择前置类型
    @Override
    public String filterType() {
//        return "pre";//4种：pre、route、post、error
        return FilterConstants.PRE_TYPE;//4种：pre、route、post、error
    }

    //过滤器顺序
    @Override
    public int filterOrder() {
        return 1;
    }

    //是否执行run返回，返回true就执行run返回，false就不执行run方法
    @Override
    public boolean shouldFilter() {
        //1、获取Request
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //2、获取URL
        String url = request.getRequestURI();
        log.info("URL={}", url);
        //3.判断是否包含在： static/**  ，/login , /register
        if(url.endsWith("/login ") || url.endsWith("/register ") || url.contains("/static/") ){
            //不需要做登录校验
            return false;
        }
        //要做登录检查的返回true
        return true;
    }

    //主业务逻辑：做登录校验
    @Override
    public Object run() throws ZuulException {
        //1、获取Request
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String url = request.getRequestURI();
        //做权限拦截
        //获取当前用户信息
        //拿到token 通过token 去reids获取用户信息
        //通过用户信息查询角色,通过角色查询对应的权限
        //通过权限集合去比对当前的url有没有访问权限,如果有,放行 return null
        //没有 直接抛异常
        HttpServletResponse response = context.getResponse();
        //设置中文编码
        response.setContentType("application/json;charset=utf-8");
        //2、从请求头中获取Token
        String token = request.getHeader("token");
        log.info("token={}", token);
        //3、判断有没有token
        if(!StringUtils.hasLength(token)){
            //登录失败，返回提示话术
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回未登录的错误码
            try {
                response.getWriter().println("请登录");
            }catch (Exception e){
                e.printStackTrace();
            }
            //4、阻止filter继续往后执行
            context.setSendZuulResponse(false);
        }
        //这里的返回结果没有任何意义，不用管
        return null;
    }
}